package com.aiwu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.aiwu.bean.ScreenConfig;
import com.aiwu.library.ui.pop.EditConfigNamePop;
import com.aiwu.library.util.DialogUtil;
import com.aiwu.library.util.ToastUtil;
import com.aiwu.widget.ScreenViewGroup;

import org.citra.citra_emu.R;

/**
 * 屏幕编辑
 */
public class ScreenEditActivity extends Activity implements ScreenViewGroup.OnActionListener {
    private static final String EXTRA_ID = "extra_id";
    private static final String EXTRA_IS_INSERT = "extra_is_insert";
    public static final int REQUEST_CODE = 1001;
    public static final String RESULT_ACTION = "result_action";
    public static final String RESULT_ID = "result_id";
    public static final int RESULT_INSERTED = 100;
    public static final int RESULT_EDITED = 101;

    private View mDecorView;
    private ScreenViewGroup screenViewGroup;
    //配置id
    private int mConfigId;
    //新建配置
    private boolean mIsInsert;

    /**
     * 外部启动
     *
     * @param activity
     * @param id       配置id
     * @param isInsert 是不是新建
     */
    public static void launch(Activity activity, int id, boolean isInsert) {
        Intent launcher = new Intent(activity, ScreenEditActivity.class);
        launcher.putExtra(EXTRA_ID, id);
        launcher.putExtra(EXTRA_IS_INSERT, isInsert);
        activity.startActivityForResult(launcher, REQUEST_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDecorView = getWindow().getDecorView();
        mDecorView.setOnSystemUiVisibilityChangeListener(visibility -> {
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                Handler handler = new Handler(getMainLooper());
                handler.postDelayed(this::enableFullscreenImmersive, 3000 /* 3s */);
            }
        });
        enableFullscreenImmersive();
        setContentView(R.layout.activity_screen_edit);
        mConfigId = getIntent().getIntExtra(EXTRA_ID, -1);
        mIsInsert = getIntent().getBooleanExtra(EXTRA_IS_INSERT, true);
        if (mConfigId == -1) {
            errorFinish();
            return;
        }
        initView();
        initData();
    }

    private void initView() {
        screenViewGroup = findViewById(R.id.screen_view_group);
        screenViewGroup.setOnActionListener(this);
    }

    private void initData() {
        if (mIsInsert) {//新建
            screenViewGroup.post(() -> screenViewGroup.addDefaultScreenView());
        } else {//编辑
            ScreenConfig screenConfig = PrefsHelper.getInstance().getScreenConfig(mConfigId);
            if (screenConfig != null) {
                screenViewGroup.post(() -> screenViewGroup.addExistingScreenView(screenConfig.getTopLeft(), screenConfig.getTopTop(), screenConfig.getTopRight(), screenConfig.getTopBottom(), screenConfig.getBottomLeft(), screenConfig.getBottomTop(), screenConfig.getBottomRight(), screenConfig.getBottomBottom()));
            } else {
                errorFinish();
            }
        }
    }

    private void errorFinish() {
        ToastUtil.toast("获取参数出错!");
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    private void successFinish() {
        Intent data = new Intent();
        data.putExtra(RESULT_ACTION, mIsInsert ? RESULT_INSERTED : RESULT_EDITED);
        data.putExtra(RESULT_ID, mConfigId);
        setResult(Activity.RESULT_OK, data);
        finish();
    }

    @Override
    public void onBackPressed() {
        showSaveConfigTip();
    }

    @Override
    public void showSaveConfigTip() {
        DialogUtil.showTip(this, R.string.save_config_tip, v -> {
            if (mIsInsert) {
                showInputNameTip();
            } else {
                saveConfigValue();
            }
        }, v -> {
            setResult(Activity.RESULT_CANCELED);
            finish();
        });
    }

    @Override
    public void resetScreenView() {
        if (mIsInsert) {
            screenViewGroup.resetDefaultScreenView();
        } else {
            ScreenConfig screenConfig = PrefsHelper.getInstance().getScreenConfig(mConfigId);
            if (screenConfig != null) {
                screenViewGroup.resetExistingScreenView(screenConfig.getTopLeft(), screenConfig.getTopTop(), screenConfig.getTopRight(), screenConfig.getTopBottom(), screenConfig.getBottomLeft(), screenConfig.getBottomTop(), screenConfig.getBottomRight(), screenConfig.getBottomBottom());
            }
        }
    }

    /**
     * 命名弹窗
     */
    private void showInputNameTip() {
        final EditConfigNamePop namePop = new EditConfigNamePop(this) {
            @Override
            protected void initView() {
                final TextView tvTitle = findViewById(R.id.tv_title);
                tvTitle.setText("输入配置名称");
                final EditText et = findViewById(R.id.et);
                et.setHint("输入配置名");
                Button btnCancel = findViewById(R.id.btn_cancel);
                Button btnConfirm = findViewById(R.id.btn_confirm);
                btnCancel.setOnClickListener(v -> dismiss());
                btnConfirm.setOnClickListener(v -> {
                    String newName = et.getText().toString();
                    if (TextUtils.isEmpty(newName)) {
                        ToastUtil.toast(R.string.config_name_empty);
                        return;
                    }
                    dismiss();
                    saveNewConfig(newName);
                });
            }
        };
        namePop.show();
    }

    /**
     * 保存新配置
     */
    private void saveNewConfig(String name) {
        if (screenViewGroup == null || screenViewGroup.getResultLocation().length != 8) {
            return;
        }
        int[] result = screenViewGroup.getResultLocation();
        PrefsHelper.getInstance().saveNewScreenConfig(mConfigId, name, result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]);
        successFinish();
    }

    /**
     * 保存配置
     */
    private void saveConfigValue() {
        if (screenViewGroup == null || screenViewGroup.getResultLocation().length != 8) {
            return;
        }
        int[] result = screenViewGroup.getResultLocation();
        PrefsHelper.getInstance().editScreenConfigValue(mConfigId, result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]);
        successFinish();
    }

    private void enableFullscreenImmersive() {
        // It would be nice to use IMMERSIVE_STICKY, but that doesn't show the toolbar.
        if (mDecorView != null) {
            mDecorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}
